﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AUSRIS.Data.Web.Entities
{
	/// <summary>
	/// <para>
	/// Collection of <see cref="Folder"/> objects
	/// </para>
	/// </summary>
	public class FolderCollection : Dictionary<String, Folder>
	{
		// TODO: Document FolderCollection class
		
		#region Public Methods

		
		public Folder GetByPath(string keyPath)
		{
			foreach(Folder f in this.Values)
			{
				if(String.Compare(f.Path, keyPath, true) == 0)
				{
					return f;
				}
			}
			return null;
		}

		public void AddFolder(string fromPath)
		{
			Folder newFolder = null;
			string[] folders = fromPath.Split(new char[] { '/', '\\' });
			if(folders.Length == 0)
			{
				throw new ArgumentException("fromPath");
			}
			if(folders.Length == 1)
			{
				newFolder = new Folder(folders[0]);
				this.Add(newFolder.Path, newFolder);
			}
			else
			{
				string parentKeyPath = fromPath.Substring(0, fromPath.LastIndexOf(@"/"));
				newFolder = new Folder(folders[folders.Length - 1], this.GetByPath(parentKeyPath));
				this.Add(newFolder.Path, newFolder);
			}
		}

		public void AddFoldersInPath(string fromPath)
		{
			string[] folders = fromPath.Split(new char[] { '/', '\\' });
			StringBuilder testPath = new StringBuilder();
			for(int x = 0; x <= folders.Length - 1; x++)
			{
				string folderName = folders[x];
				if(folderName.Length == 0)
					continue;
				if(x > 0)
				{
					testPath.AppendFormat("/{0}", folderName);
				}
				else
				{
					testPath.Append(folderName);
				}
				if(this.GetByPath(testPath.ToString()) == null)
				{
					this.AddFolder(testPath.ToString());
				}
			}
		}

		public IList<Folder> GetFlatList()
		{
			List<Folder> list = new List<Folder>(this.Values);
			list.Sort();
			return list;
		}

		public IList<Folder> GetTopFolders()
		{
			List<Folder> list = new List<Folder>();
			foreach(Folder folder in this.GetFlatList())
			{
				if(folder.ParentFolder == null)
				{
					list.Add(folder);
				}
			}
			return list;
		}

		#endregion
	}
}